package com.zfsbs.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.model.SbsPrinterData;
import com.tool.utils.activityManager.AppManager;
import com.tool.utils.utils.ALog;
import com.tool.utils.utils.FyAidlUtils;
import com.tool.utils.utils.LogUtils;
import com.tool.utils.utils.SPUtils;
import com.tool.utils.utils.StringUtils;
import com.tool.utils.utils.ToastUtils;
import com.tool.utils.utils.ToolNewLand;
import com.zfsbs.R;
import com.zfsbs.common.CommonFunc;
import com.zfsbs.config.Constants;
import com.zfsbs.core.action.FyBat;
import com.zfsbs.core.action.FyPrintUtils;
import com.zfsbs.core.myinterface.ActionCallbackListener;
import com.zfsbs.model.ChargeBlance;
import com.zfsbs.model.FailureData;
import com.zfsbs.model.FyMicropayRequest;
import com.zfsbs.model.FyMicropayResponse;
import com.zfsbs.model.FyQueryRequest;
import com.zfsbs.model.FyQueryResponse;
import com.zfsbs.model.FyRefundResponse;
import com.zfsbs.model.RechargeUpLoad;
import com.zfsbs.model.SmFyResponse;
import com.zfsbs.model.SmResponse;
import com.zfsbs.model.TransUploadRequest;
import com.zfsbs.myapplication.MyApplication;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import static com.zfsbs.config.Constants.PAY_FY_ALY;
import static com.zfsbs.config.Constants.PAY_FY_UNION;
import static com.zfsbs.config.Constants.PAY_FY_WX;
import static com.zfsbs.config.Constants.REQUEST_CAPTURE_QB;
import static com.zfsbs.config.Constants.REQUEST_CAPTURE_UNIPAY;
import static com.zfsbs.config.Constants.REQUEST_CASH;
import static com.zfsbs.config.Constants.REQUEST_flot_CASH;


public class ZfPayRechargeActivity extends BaseActivity implements View.OnClickListener {

//    private FyBat fybat;

//    private RechargeAmount vo;
    private String cardNo;
    private String tgy;
//    private String cardId;
    private String oldAmount;
    private String actualAmount;
    private String orderNo;

    private LinearLayout ll_payType;
    private LinearLayout ll_payFinish;
    private LinearLayout ll_no_pay_amount;
    private LinearLayout ll_payQuery;

    private TextView orderAmount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_recharge_pay);
//        AppManager.getAppManager().addActivity(this);
        initTitle("选择充值方式");

        initData();
        initView();

    }

    private void initData() {

        cardNo = getIntent().getBundleExtra("data").getString("cardNo");
        tgy = getIntent().getBundleExtra("data").getString("tgy");
        oldAmount = getIntent().getBundleExtra("data").getString("oldAmount");
        actualAmount = getIntent().getBundleExtra("data").getString("actualAmount");
        orderNo = getIntent().getBundleExtra("data").getString("orderNo");

//        cardId = getIntent().getBundleExtra("data").getString("card_id");
//        vo = (RechargeAmount) getIntent().getBundleExtra("data").getSerializable("RechargeAmount");
//        if (vo == null){
//            ToastUtils.CustomShow(mContext, "数据有误");
//            onBackPressed();
//            return;
//        }

//        fybat = new FyBat(this, listener1);
    }

    private void initView() {

        orderAmount = (TextView) findViewById(R.id.id_order_amount);
        orderAmount.setText(StringUtils.formatStrMoney(oldAmount));

        textView(R.id.id_dz_amount).setText(StringUtils.formatStrMoney(actualAmount));
        TextView etCardNo = textView(R.id.id_memberCardNo);
        etCardNo.setText(cardNo);


        ll_payType = (LinearLayout) findViewById(R.id.ll_pay_type);
        ll_payFinish = (LinearLayout) findViewById(R.id.ll_pay_finish);
        ll_payQuery = (LinearLayout) findViewById(R.id.ll_pay_query);
        ll_no_pay_amount = (LinearLayout) findViewById(R.id.ll_no_pay_amount);

        linearLayout(R.id.pay_wx).setOnClickListener(this);
        linearLayout(R.id.pay_aly).setOnClickListener(this);
        linearLayout(R.id.pay_cash).setOnClickListener(this);
        linearLayout(R.id.id_pay_flot).setOnClickListener(this);
        linearLayout(R.id.id_ll_unionpay).setOnClickListener(this);

        linearLayout(R.id.id_ll_unionpay).setVisibility(View.INVISIBLE);

        button(R.id.id_print).setOnClickListener(this);
        button(R.id.id_finish).setOnClickListener(this);
        button(R.id.id_query).setOnClickListener(this);
        button(R.id.id_terminal_query_sure).setOnClickListener(this);

    }






    private void showLayoutEndQuery() {
        ll_payType.setVisibility(View.GONE);
        ll_payQuery.setVisibility(View.VISIBLE);
    }

    private void showLayout() {
        ll_payType.setVisibility(View.GONE);
        ll_payFinish.setVisibility(View.VISIBLE);
    }




    private void setCashPrintData1(int oddChangeAmout, int payType) {
        printerData.setMerchantName(MyApplication.getInstance().getLoginData().getTerminalName());
        printerData.setMerchantNo(MyApplication.getInstance().getLoginData().getMerchantNo());
        printerData.setTerminalId(StringUtils.getSerial());
        printerData.setOperatorNo((String) SPUtils.get(this, Constants.USER_NAME, ""));
        printerData.setDateTime(StringUtils.getCurTime());
        printerData.setAmount(StringUtils.formatStrMoney(oldAmount));
        printerData.setReceiveAmount(StringUtils.formatStrMoney(actualAmount));
        printerData.setOddChangeAmout(StringUtils.formatIntMoney(oddChangeAmout));
        printerData.setPayType(payType);

    }

    /**
     * 现金
     *
     * @param oddChangeAmout
     */
    private void payCash1(int oddChangeAmout, int payType) {

        //设置打印信息
        setCashPrintData1(oddChangeAmout, payType);

        //打印订单号与流水上送统一
        printerData.setClientOrderNo(orderNo);

        //流水上送
        RechargeUpLoad rechargeUpLoad = new RechargeUpLoad();
        rechargeUpLoad.setSid(MyApplication.getInstance().getLoginData().getSid());
        rechargeUpLoad.setPayAmount(Integer.parseInt(oldAmount));
        rechargeUpLoad.setOrderNo(printerData.getClientOrderNo());
        rechargeUpLoad.setActivateCode(MyApplication.getInstance().getLoginData().getTerminalNo());
        rechargeUpLoad.setMerchantNo(MyApplication.getInstance().getLoginData().getMerchantNo());
        rechargeUpLoad.setT(StringUtils.getdate2TimeStamp(printerData.getDateTime()));
        rechargeUpLoad.setSerialNum(StringUtils.getSerial());
        rechargeUpLoad.setPayType(printerData.getPayType());
        rechargeUpLoad.setOperator_num((String) SPUtils.get(mContext, Constants.USER_NAME, ""));
        rechargeUpLoad.setPayType(Constants.PAY_WAY_CASH);
        rechargeUpLoad.setPromotion_num(tgy);

        rechargeUpload(rechargeUpLoad);

    }

    @Override
    public void onClick(View view) {

        String amt = StringUtils.fillZero(oldAmount+"", 12);


        switch (view.getId()) {
            case R.id.id_ll_unionpay:
//                CommonFunc.startResultAction(ZfPayRechargeActivity.this, CaptureActivity.class, null, REQUEST_CAPTURE_UNIPAY);
                break;
            case R.id.pay_wx:
//                CommonFunc.startResultAction(ZfPayRechargeActivity.this, CaptureActivity.class, null, REQUEST_CAPTURE_WX);
//                CommonFunc.pay(this, 11, "660000", StringUtils.formatStrMoney(oldAmount), orderNo);
                Intent intent10 = new Intent();
                intent10.setComponent(new ComponentName("com.fuyousf.android.fuious","com.fuyousf.android.fuious.MainActivity"));
                //包名     包名+类名（全路径）
                intent10.putExtra("transName", "微信消费");
                intent10.putExtra("amount", amt);
                intent10.putExtra("isPrintTicket", "true");
                intent10.putExtra("orderNumber", orderNo);
                intent10.putExtra("version", "1.0.7");
                startActivityForResult(intent10, Constants.PAY_WAY_RECHARGE_WX);
                break;
            case R.id.pay_aly:
//                CommonFunc.startResultAction(ZfPayRechargeActivity.this, CaptureActivity.class, null, REQUEST_CAPTURE_ALY);
//                CommonFunc.pay(this, 12, "660000", StringUtils.formatStrMoney(oldAmount), orderNo);
                Intent intent5 = new Intent();
                intent5.setComponent(new ComponentName("com.fuyousf.android.fuious","com.fuyousf.android.fuious.MainActivity"));
                //包名     包名+类名（全路径）
                intent5.putExtra("amount", amt);
                intent5.putExtra("transName", "支付宝消费");
                intent5.putExtra("isPrintTicket", "true");
                intent5.putExtra("orderNumber", orderNo);
                intent5.putExtra("version", "1.0.7");
                startActivityForResult(intent5, Constants.PAY_WAY_RECHARGE_ALY);
                break;
            case R.id.pay_cash: {
                Bundle bundle = new Bundle();
                bundle.putString("amount", orderAmount.getText().toString());
                CommonFunc.startResultAction(this, ZfPayCashActivity.class, bundle, REQUEST_CASH);
            }
                break;
            case R.id.id_pay_flot:
                payflot1();
                break;
            case R.id.id_print:
//                Printer.print(printerData, ZfPayRechargeActivity.this);
//                ToolNewLand.getToolNewLand().printText(printerData);
//                print(mContext,printerData);

                if (printerData.getPayType() == Constants.PAY_WAY_RECHARGE_FLOT) {
//                            CommonFunc.query(this, 0, printerData.getClientOrderNo(), printerData.getBatchNO() + printerData.getVoucherNo());
                    Intent intent23 = new Intent();
                    intent23.setComponent(new ComponentName("com.fuyousf.android.fuious","com.fuyousf.android.fuious.MainActivity"));

                    //包名     包名+类名（全路径）
                    intent23.putExtra("transName", "打印最后一笔");
                    startActivityForResult(intent23, 99);
                } else if (printerData.getPayType() == Constants.PAY_WAY_RECHARGE_ALY || printerData.getPayType() == Constants.PAY_WAY_RECHARGE_WX){
//                            CommonFunc.query(this, 1, printerData.getClientOrderNo(), printerData.getBatchNO() + printerData.getVoucherNo());
                    Intent intent23 = new Intent();
                    intent23.setComponent(new ComponentName("com.fuyousf.android.fuious","com.fuyousf.android.fuious.MainActivity"));

                    //包名     包名+类名（全路径）
                    intent23.putExtra("transName", "打印最后一笔");
                    startActivityForResult(intent23, 99);
                }else{
                    print(mContext,printerData);
                }

                break;

            case R.id.id_query:
//                setLastQuerySend1();
                break;
            case R.id.id_finish:
            case R.id.id_terminal_query_sure:
                finish();
                break;
            default:
                break;
        }
    }



    /**
     * 刷卡
     */
    private void payflot1() {
//        CommonFunc.pay(this, 0, "000000", StringUtils.formatStrMoney(oldAmount), orderNo);

        String amt = StringUtils.fillZero(oldAmount+"", 12);

        Intent intent4 = new Intent();
        intent4.setComponent(new ComponentName("com.fuyousf.android.fuious","com.fuyousf.android.fuious.MainActivity"));

        //包名     包名+类名（全路径）
        intent4.putExtra("amount", amt);
        intent4.putExtra("transName", "消费");
        intent4.putExtra("orderNumber", orderNo);
        intent4.putExtra("version","1.0.7");

        startActivityForResult(intent4, Constants.PAY_WAY_RECHARGE_FLOT);
    }



//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//
//        if (requestCode == 1 && data != null) {
//
//            switch (resultCode) {
//                case Activity.RESULT_OK:
//
//                    LogUtils.e("msg_tp:" + data.getStringExtra("msg_tp") + "\n" +
//                            "pay_tp:" + data.getStringExtra("pay_tp") + "\n" +
//                            "proc_tp:" + data.getStringExtra("proc_tp") + "\n" +
//                            "proc_cd:" + data.getStringExtra("proc_cd") + "\n" +
//                            "amt:" + data.getStringExtra("amt") + "\n" +
//                            "systraceno:" + data.getStringExtra("systraceno") + "\n" +
//                            "sysoldtraceno:" + data.getStringExtra("sysoldtraceno") + "\n" +
//                            "order_no:" + data.getStringExtra("order_no") + "\n" +
//                            "appid:" + data.getStringExtra("appid") + "\n" +
//                            "time_stamp:" + data.getStringExtra("time_stamp") + "\n" +
//                            "print_info:" + data.getStringExtra("print_info") + "\n" +
//                            "batchbillno:" + data.getStringExtra("batchbillno") + "\n" +
//                            "merid:" + data.getStringExtra("merid") + "\n" +
//                            "termid:" + data.getStringExtra("termid") + "\n");
//
////                    LogUtils.e("txndetail:" + data.getExtras().getString("txndetail"));
//
//                    ALog.json("txndetail", data.getExtras().getString("txndetail"));
//
//                    String payType = data.getStringExtra("pay_tp");
//                    String detail = data.getExtras().getString("txndetail");
//                    if ("0".equals(payType)){ //银行卡
//                        setFlot(detail);
//                    } else if ("1".equals(payType)){ //微信
//                        setSmPay(detail, Constants.PAY_WAY_RECHARGE_WX,  Constants.PAY_WAY_WX);
//                    } else if ("2".equals(payType)){ //支付宝
//                        setSmPay(detail, Constants.PAY_WAY_RECHARGE_ALY, Constants.PAY_WAY_ALY);
//                    }
//                    break;
//                case Activity.RESULT_CANCELED:
////                    mTvResult.setText("reason:" + data.getStringExtra("reason"));
//                    ToastUtils.CustomShow(mContext, data.getStringExtra("reason"));
//                    break;
//                case -2:
////                    mTvResult.setText("reason" + data.getStringExtra("reason"));
//                    ToastUtils.CustomShow(mContext, data.getStringExtra("reason"));
//                    break;
//                default:
//                    break;
//            }
//        }else {
//
//            if (resultCode != RESULT_OK) {
//                return;
//            }
//            switch (requestCode) {
//                case REQUEST_flot_CASH: {
//                    int oddChangeAmout = data.getBundleExtra("bundle").getInt("oddChangeAmout");
//
//                    payCash1(oddChangeAmout, Constants.PAY_WAY_PAY_FLOT);
//                }
//                break;
//                case REQUEST_CASH: {
//                    int oddChangeAmout = data.getBundleExtra("bundle").getInt("oddChangeAmout");
//
//                    payCash1(oddChangeAmout, Constants.PAY_WAY_RECHARGE_CASH);
//                }
//                default:
//                    break;
//            }
//        }
//    }




    @SuppressLint("WrongConstant")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("Fuiou", "resultCode--返回值："+resultCode);
        Log.e("TAG", "resultCode--返回值："+resultCode);
        if ((requestCode == Constants.PAY_WAY_RECHARGE_WX || requestCode == Constants.PAY_WAY_RECHARGE_ALY || requestCode == Constants.PAY_WAY_RECHARGE_FLOT || requestCode == 99) && data != null) {
            switch (resultCode) {
                case Activity.RESULT_CANCELED:
                    String reason = "";
                    String traceNo = "";
                    String batchNo = "";
                    String ordernumber = "";
                    if (data != null) {
                        Bundle b = data.getExtras();
                        if (b != null) {
                            reason = (String) b.get("reason");
                            traceNo = (String) b.getString("traceNo");
                            batchNo = (String) b.getString("batchNo");
                            ordernumber = (String) b.getString("ordernumber");
                        }
                    }
                    if (reason != null) {
                        Log.d("reason", reason);
                        Toast.makeText(this, reason, Toast.LENGTH_SHORT).show();
                    }
                    Log.e("TAG", "失败返回值--reason--返回值：" + reason + "/n 凭证号：" + traceNo + "/n 批次号：" + batchNo + "/n 订单号：" + ordernumber);

                    break;
                case Activity.RESULT_OK:
                    String print = data.getStringExtra("reason");//打印成功返回数据
                    Log.e("TAG", "成功返回值--reason--返回值：" + print);

                    String b = data.getStringExtra("batchNo");//批次号
                    String c = data.getStringExtra("traceNo");//流水号
                    String d = data.getStringExtra("cardNo");//卡号

                    String e = data.getStringExtra("merchantId");//商户号
                    String f = data.getStringExtra("terminalId");//终端号

                    String g = data.getStringExtra("referenceNo");//参考号
                    String h = data.getStringExtra("issue");//发卡行
                    String i = data.getStringExtra("type");//卡类型
                    String j = data.getStringExtra("date");//日期
                    String k = data.getStringExtra("time");//时间

                    String l = data.getStringExtra("wireless.apn");//apn
                    String m = data.getStringExtra("wireless.username");//用户名
                    String n = data.getStringExtra("wireless.password");//密码
                    String o = data.getStringExtra("wireless.apnEnabled");//Apn是否开启
                    String p = data.getStringExtra("merchantName");//商户名

                    String r = data.getStringExtra("oldReferenceNo");//原参考号

                    String t = data.getStringExtra("orderNumber");
                    String tzfb = data.getStringExtra("zfbOrderNumber");
                    String twx = data.getStringExtra("wxOrderNumber");

                    String u = data.getStringExtra("oldOrderNumber");
                    String sWx = data.getStringExtra("wxOldOrderNumber");
                    String sZfb = data.getStringExtra("zfbOldOrderNumber");

                    String wMb = data.getStringExtra("zfbMbOldOrderNumber");
                    String zMb = data.getStringExtra("wxMbOldOrderNumber");

                    String tui = data.getStringExtra("tuiOldOrderNumber");

                    String settleData = data.getStringExtra("settleJson");
                    String json = data.getStringExtra("json");

                    String return_Code = data.getStringExtra("return_txt");//扫码返回数据

                    String authorizationCode = data.getStringExtra("authorizationCode");//预授权 授权码

                    String backOldReferenceNo = data.getStringExtra("backOldReferenceNo");//退货的原参考号

                    String referenceNoSuccess = data.getStringExtra("referenceNoSuccess");//订单查询返回参考号

                    String oldReferenceNoSuccess = data.getStringExtra("oldReferenceNoSuccess");//订单查询返回原参考号

                    String amount = data.getStringExtra("amount");//金额

                    String acqId = data.getStringExtra("acqId");//收单行

                    String expiredDate = data.getStringExtra("expiredDate");//卡有效期

                    String transactionType = data.getStringExtra("transactionType"); //交易类型

                    JSONObject jsO = new JSONObject();
                    try {
                        jsO.put("reason", print);
                        jsO.put("batchNo", b);//批次号
                        jsO.put("traceNo", c);//流水号
                        jsO.put("cardNo", d);//卡号
                        jsO.put("merchantId", e);//商户号
                        jsO.put("terminalId", f);//终端号
                        jsO.put("referenceNo", g);//参考号
                        jsO.put("issue", h);//发卡行
                        jsO.put("type", i);//卡类型
                        jsO.put("date", j);//日期
                        jsO.put("time", k);//时间
                        jsO.put("wireless.apn", l);//apn
                        jsO.put("wireless.username", m);//用户名
                        jsO.put("wireless.password", n);//密码
                        jsO.put("wireless.apnEnabled", o);//Apn是否开启
                        jsO.put("merchantName", p);//商户名
                        jsO.put("oldReferenceNo", r);//原参考号
                        jsO.put("backOldReferenceNo", backOldReferenceNo);//退货原参考号
                        jsO.put("orderNumber", t);//消费订单号
                        jsO.put("zfbOrderNumber", tzfb);//支付宝消费订单号
                        jsO.put("wxOrderNumber", twx);//微信消费订单号
                        jsO.put("oldOrderNumber", u);//原消费订单号
                        jsO.put("wxOldOrderNumber", sWx);//原支付宝消费订单号
                        jsO.put("zfbOldOrderNumber", sZfb);//原微信消费订单号
                        jsO.put("zfbMbOldOrderNumber", wMb);//原支付宝末笔订单号
                        jsO.put("wxMbOldOrderNumber", zMb);//原微信末笔订单号
                        jsO.put("tuiOldOrderNumber", tui);//退款订单号
                        jsO.put("return_txt", return_Code);//扫码返回数据
                        jsO.put("authorizationCode", authorizationCode);//授权码
                        jsO.put("referenceNoSuccess", referenceNoSuccess);//订单查询参考号
                        jsO.put("oldReferenceNoSuccess", oldReferenceNoSuccess);//订单查询原参考号
                        jsO.put("amount", amount);
                        jsO.put("acqId", acqId);
                        jsO.put("expiredDate", expiredDate);
                        jsO.put("settleJson", settleData);
                        jsO.put("json", json);
                        jsO.put("transactionType", transactionType);

                    } catch (JSONException e1) {
                        e1.printStackTrace();
                    }


                    ALog.json(jsO.toString());


                    if (requestCode == Constants.PAY_WAY_RECHARGE_FLOT){
                        setFlot(jsO.toString());
                    }else if (requestCode == Constants.PAY_WAY_RECHARGE_ALY){
                        setSmPay(jsO.toString(), Constants.PAY_WAY_RECHARGE_ALY, Constants.PAY_WAY_ALY);
//                        setSmPay(jsO.toString(), Constants.PAY_WAY_ALY);
                    }else if (requestCode == Constants.PAY_WAY_RECHARGE_WX){
                        setSmPay(jsO.toString(), Constants.PAY_WAY_RECHARGE_WX,  Constants.PAY_WAY_WX);
//                        setSmPay(jsO.toString(), Constants.PAY_WAY_WX);
                    }else if (requestCode == 99){
//                        Gson gson = new Gson();
//                        TransUploadRequest request = gson.fromJson(printerData.getTransUploadData(), TransUploadRequest.class);
//                        ALog.json(request.toString());
//                        getPrinterData(request);
                        print(mContext,printerData);

                    }


                    break;
            }
        }else{
            if (resultCode != RESULT_OK) {
                return;
            }
            switch (requestCode) {
                case REQUEST_CASH: {
                    int oddChangeAmout = data.getBundleExtra("bundle").getInt("oddChangeAmout");
                    payCash1(oddChangeAmout, Constants.PAY_WAY_PAY_FLOT);
                }
                    break;
                case REQUEST_flot_CASH: {
                    int oddChangeAmout = data.getBundleExtra("bundle").getInt("oddChangeAmout");

                    payCash1(oddChangeAmout, Constants.PAY_WAY_PAY_FLOT);
                }
                break;
                default:
                    break;
            }
        }
    }

    private void setFlot(String data){

        Gson gson = new Gson();
        SmFyResponse smResponse = gson.fromJson(data, SmFyResponse.class);

        printerData.setMerchantName(smResponse.getMerchantName());
        printerData.setMerchantNo(smResponse.getMerchantId());//(transInfo.getMid());
        printerData.setTerminalId(smResponse.getTerminalId());
        printerData.setOperatorNo((String) SPUtils.get(this, Constants.USER_NAME, ""));
//        printerData.setAcquirer(smResponse.getAcqno());
        printerData.setIssuer(smResponse.getIssue());
        printerData.setCardNo(smResponse.getCardNo());
        printerData.setTransType(1 + "");
//        printerData.setExpDate(smResponse.getExpdate());
        printerData.setBatchNO(smResponse.getBatchNo());
        printerData.setVoucherNo(smResponse.getTraceNo());
        printerData.setDateTime(
                StringUtils.formatTime(StringUtils.getCurYear()+smResponse.getDate()+smResponse.getTime()));
//        printerData.setAuthNo(smResponse.getAuthcode());
        printerData.setReferNo(smResponse.getReferenceNo());
        printerData.setOrderAmount(Integer.parseInt(actualAmount));
        printerData.setAmount(StringUtils.formatIntMoney(Long.parseLong(smResponse.getAmount())));
        printerData.setPayType(Constants.PAY_WAY_RECHARGE_FLOT);


        printerData.setClientOrderNo(orderNo);


        //流水上送
        RechargeUpLoad rechargeUpLoad = new RechargeUpLoad();
        rechargeUpLoad.setSid(MyApplication.getInstance().getLoginData().getSid());
        rechargeUpLoad.setPayAmount(Integer.parseInt(oldAmount));
        rechargeUpLoad.setOrderNo(printerData.getClientOrderNo());
        rechargeUpLoad.setActivateCode(MyApplication.getInstance().getLoginData().getActiveCode());
        rechargeUpLoad.setMerchantNo(MyApplication.getInstance().getLoginData().getFyMerchantNo());
        rechargeUpLoad.setT(StringUtils.getdate2TimeStamp(printerData.getDateTime()));
        rechargeUpLoad.setSerialNum(StringUtils.getSerial());
        rechargeUpLoad.setPayType(printerData.getPayType());
        rechargeUpLoad.setOperator_num((String) SPUtils.get(mContext, Constants.USER_NAME, ""));


        rechargeUpLoad.setPayType(Constants.PAY_WAY_FLOT);

        rechargeUpLoad.setPromotion_num(tgy);
        rechargeUpLoad.setTransNo(printerData.getTransNo());
        rechargeUpLoad.setAuthCode(printerData.getAuthCode());


        rechargeUpload(rechargeUpLoad);
    }


    private void setSmPay(String data, int payType, int UploadType){

        Gson gson = new Gson();
        SmFyResponse smResponse = gson.fromJson(data, SmFyResponse.class);



        printerData.setMerchantName(smResponse.getMerchantName());
        printerData.setMerchantNo(smResponse.getMerchantId());
        printerData.setTerminalId(smResponse.getTerminalId());
        printerData.setOperatorNo((String) SPUtils.get(this, Constants.USER_NAME, ""));
        printerData.setTransNo(smResponse.getTraceNo());
        printerData.setAuthCode(smResponse.getReferenceNo());
        printerData.setDateTime(StringUtils.formatTime(StringUtils.getCurYear()+smResponse.getDate()+smResponse.getTime()));
        printerData.setOrderAmount(Integer.parseInt(actualAmount));
        printerData.setAmount(StringUtils.formatIntMoney(Long.parseLong(smResponse.getAmount())));
        printerData.setScanPayType(MyApplication.getInstance().getLoginData().getScanPayType());

        printerData.setPayType(payType);

        printerData.setClientOrderNo(orderNo);

        //流水上送
        RechargeUpLoad rechargeUpLoad = new RechargeUpLoad();

        rechargeUpLoad.setSid(MyApplication.getInstance().getLoginData().getSid());
        rechargeUpLoad.setPayAmount(Integer.parseInt(oldAmount));
        rechargeUpLoad.setOrderNo(printerData.getClientOrderNo());
        rechargeUpLoad.setActivateCode(MyApplication.getInstance().getLoginData().getActiveCode());
        rechargeUpLoad.setMerchantNo(MyApplication.getInstance().getLoginData().getFyMerchantNo());
        rechargeUpLoad.setT(StringUtils.getdate2TimeStamp(printerData.getDateTime()));
        rechargeUpLoad.setSerialNum(StringUtils.getSerial());
        rechargeUpLoad.setPayType(printerData.getPayType());
        rechargeUpLoad.setOperator_num((String) SPUtils.get(mContext, Constants.USER_NAME, ""));

        //这个地方支付与充值传的是一样

        rechargeUpLoad.setPayType(UploadType);

        rechargeUpLoad.setPromotion_num(tgy);
        rechargeUpLoad.setTransNo(printerData.getTransNo());
        rechargeUpLoad.setAuthCode(printerData.getAuthCode());

        rechargeUpload(rechargeUpLoad);
    }












    /**
     * 将流水上送的数据转成字串保存在打印的对象中
     * 不管成功失败，流水上送的数据保存下来
     *
     * @param request
     */
    private void setRechargeUpLoadData(RechargeUpLoad request) {
        Gson gson = new Gson();
        String data = gson.toJson(request);
        ALog.json(data);
        printerData.setRechargeUpload(data);
    }


    private void print(Context context, SbsPrinterData data){
        if (FyAidlUtils.getPrintService() != null){
            String jsonDate = FyPrintUtils.printText(context, data);
            Log.e("TAG", "json："+jsonDate);
            if (StringUtils.isBlank(jsonDate)){
                return;
            }
            try {
                FyAidlUtils.getPrintService().print(jsonDate);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }



    private void rechargeUpload(final RechargeUpLoad rechargeUpLoad){
        sbsAction.rechargePay(mContext, rechargeUpLoad, new ActionCallbackListener<ChargeBlance>() {
            @Override
            public void onSuccess(ChargeBlance data) {
                setRechargeUpLoadData(rechargeUpLoad);
                printerData.setPromotion_num(rechargeUpLoad.getPromotion_num());
                printerData.setPacektRemian(data.getPacektRemian());
                printerData.setRealize_card_num(data.getRealize_card_num());
                printerData.setMember_name(data.getMember_name());
                PrinterDataSave();

                showLayout();

                // 打印
//                ToolNewLand.getToolNewLand().printText(printerData);

                print(mContext,printerData);
            }

            @Override
            public void onFailure(String errorEvent, String message) {
                ToastUtils.CustomShow(ZfPayRechargeActivity.this, errorEvent + "#" + message);
                showLayout();
                setRechargeUpLoadData(rechargeUpLoad);
                printerData.setUploadFlag(true);
                printerData.setApp_type(0);
                // 保存打印的数据，不保存图片数据
                PrinterDataSave();
                // 打印
//                ToolNewLand.getToolNewLand().printText(printerData);
                print(mContext,printerData);
            }

            @Override
            public void onFailurTimeOut(String s, String error_msg) {

            }

            @Override
            public void onLogin() {

            }
        });
    }


    /**
     * 保存数据
     */
    private void PrinterDataSave() {

        CommonFunc.ClearFailureInfo(this);
        CommonFunc.PrinterDataDelete();
        printerData.setStatus(true);
        if (printerData.save()) {
            LogUtils.e("打印数据存储成功");
        } else {
            LogUtils.e("打印数据存储失败");
        }
    }
}
